import os

from dotenv import load_dotenv

from ..models.paper_model import Paper
from sqlalchemy.orm import Session
from sqlalchemy import select, update, desc
from fastapi import HTTPException
import random

from ..utils.file_tools import delete_file
from ..utils.uploads_oss import main as upload_on_oss
from ..utils.deletes_oss import main as delete_on_oss

load_dotenv()
SOURCES_PATH=os.getenv("SOURCES_PATH")

def create_paper(db: Session, name,path,type,subject,grade,starts):
    if db.execute(select(Paper).where(Paper.name ==name)).scalars().first():
        raise HTTPException(status_code=400, detail=f"Paper {name} already exists")
    file_path=os.path.join(SOURCES_PATH, path)
    upload_on_oss(path,file_path)
    new_paper = Paper(name=name,path=path,
                      type=type,subject=subject,
                      grade=grade,starts=starts,
                      oss_url="http://whatteam1.oss-cn-beijing.aliyuncs.com/"+path)
    db.add(new_paper)
    db.commit()
    db.refresh(new_paper)
    return new_paper.as_dict()


def update_paper(db: Session, paper_id: int, subject: str = None, grade: str = None):

    # 查询教科书是否存在
    exist_paper = db.execute(select(Paper).where(Paper.id == paper_id)).scalar()
    if not exist_paper:
        raise HTTPException(status_code=404, detail=f"Paper {paper_id} not found")

    # 更新字段（如果提供了新值）
    if subject is not None:
        exist_paper.subject = subject
    if grade is not None:
        exist_paper.grade = grade
# 提交更改并刷新对象
    db.commit()
    db.refresh(exist_paper)

    return exist_paper.as_dict()
def delete_paper(db: Session, paper_id: int):
    exist_paper = db.get(Paper, paper_id)
    if not exist_paper:
        raise HTTPException(status_code=404, detail="Paper not found")
    delete_file(exist_paper.path)
    db.delete(exist_paper)
    delete_on_oss(exist_paper.path)
    db.commit()
    return exist_paper.as_dict()


def get_paper_page_subject(db:Session,subject: str, page: int = 1, page_size: int = 10):
    try:
        offset = (page - 1) * page_size
        paper_list = (
            db.query(Paper)
            .filter(Paper.subject == subject)

            .offset(offset)
            .limit(page_size)
            .all()
        )
        return paper_list
    finally:
        db.close()

def get_paper_page_grade(db:Session,grade: str, page: int = 1, page_size: int = 10):
    try:
        offset = (page - 1) * page_size
        paper_list = (
            db.query(Paper)
            .filter(Paper.grade== grade)

            .offset(offset)
            .limit(page_size)
            .all()
        )
        return paper_list
    finally:
        db.close()


def get_paper_page_grade_subject(db: Session, grade: str,subject: str, page: int = 1, page_size: int = 10):
    try:
        offset = (page - 1) * page_size
        paper_list = (
            db.query(Paper)
            .filter(Paper.grade == grade)
            .filter(Paper.subject == subject)
            .offset(offset)
            .limit(page_size)
            .all()
        )
        return paper_list
    finally:
        db.close()

def get_paper_by_id(db: Session, paper_id: int):
    paper = db.query(Paper).filter(Paper.id == paper_id).first()

    if not paper:
        return None

    data = paper.as_dict()
    # if data.get("cover"):
    #     cover_base64 = get_image_as_base64(data["cover"])
    #     data["cover"] = cover_base64 or data["cover"]  # 如果找不到图片保留原始路径

    return data

def get_paper_quantity(db: Session):
    return db.query(Paper).count()